<script lang="ts" setup>
import {
  getOneByCondition,
  getReadonly,
  insertOne,
  reSetDialogModel,
  updateOne,
  urls,
  validateRepeat
} from '@/index';

import type { DialogModel, ProjectWeldList } from '@/index.d';
import type { FormInstance, FormRules } from 'element-plus';

const dialogModel = defineModel<DialogModel<ProjectWeldList>>('dialogModel', {
  required: true
});

const { updateForbidden } = getReadonly(dialogModel.value);

const formData = reactive<ProjectWeldList>({
  id: 0,
  partQuantity: 1,
  isStatistics: true
});

const setFormData = async (res: ProjectWeldList) => {
  formData.id = res.id;
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
  formData.projectId = res.projectId;
  formData.projectName = res.projectName;
  formData.project = res.project;
  formData.componentName = res.componentName;
  formData.partName = res.partName;
  formData.partReference = res.partReference;
  formData.partThickness = res.partThickness;
  formData.partQuantity = res.partQuantity;
  formData.partType = res.partType;
  formData.weldGroove = res.weldGroove;
  formData.weldMethod = res.weldMethod;
  formData.baseMaterial1 = res.baseMaterial1;
  formData.baseMaterial2 = res.baseMaterial2;
  formData.weldMaterial = res.weldMaterial;
  formData.isStatistics = res.isStatistics;
  formData.note = res.note;
  formData.attachmentUuid = res.attachmentUuid;
  formData.attachmentUrl = res.attachmentUrl;
};

const reSetFormData = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  delete formData.projectId;
  delete formData.projectName;
  delete formData.project;
  delete formData.componentName;
  delete formData.partName;
  delete formData.partReference;
  delete formData.partThickness;
  formData.partQuantity = 1;
  delete formData.partType;
  delete formData.weldGroove;
  delete formData.weldMethod;
  delete formData.baseMaterial1;
  delete formData.baseMaterial2;
  delete formData.weldMaterial;
  delete formData.isStatistics;
  delete formData.note;
  delete formData.attachmentUuid;
  delete formData.attachmentUrl;
};

watch(
  () => dialogModel.value.visible,
  value => {
    value && (formData.id = dialogModel.value.id as number);
    !value && reSetFormData();
  },
  {
    immediate: true
  }
);

watch(
  () => formData.id,
  async (value: number | undefined) => {
    if (value) {
      const res = await getOneByCondition<ProjectWeldList>(urls.projectWeldList, 'id', value);
      res && setFormData(res);
    }
  },
  {
    immediate: true
  }
);

const formDataRef = useTemplateRef<FormInstance>('formDataRef');

interface FormDataRules {
  projectId: number;
  partName: string;
  partReference: string;
}

const validatePartName = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入工件名称'));
  } else {
    validateRepeat(urls.projectWeldList, {
      id: formData.id,
      projectId: formData.projectId,
      partName: formData.partName
    }).then(res => {
      if (res) {
        callback(new Error('工件名称重复'));
      } else {
        callback();
      }
    });
  }
};

const validatePartReference = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入工件编号'));
  } else {
    validateRepeat(urls.projectWeldList, {
      id: formData.id,
      projectId: formData.projectId,
      partReference: formData.partReference
    }).then(res => {
      if (res) {
        callback(new Error('工件编号重复'));
      } else {
        callback();
      }
    });
  }
};

const formDataRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});
    case 'insert':
      return reactive<FormRules<FormDataRules>>({
        projectId: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        partName: [{ validator: validatePartName, trigger: 'submit' }],
        partReference: [{ validator: validatePartReference, trigger: 'submit' }]
      });
    case 'update':
      return reactive<FormRules<FormDataRules>>({
        projectId: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        partName: [{ validator: validatePartName, trigger: 'submit' }],
        partReference: [{ validator: validatePartReference, trigger: 'submit' }]
      });
  }
});

const saveFormData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (dialogModel.value.id === 0) {
          const res = (await insertOne<ProjectWeldList>(
            urls.projectWeldList,
            formData
          )) as ProjectWeldList;
          if (res) {
            setFormData(res);
            dialogModel.value.id = res.id as number;
            dialogModel.value.type = 'update';
            dialogModel.value.change = true;
          }
        } else {
          const tempFormData: ProjectWeldList = {
            id: formData.id,
            projectId: formData.projectId,
            componentName: formData.componentName,
            partName: formData.partName,
            partReference: formData.partReference,
            partThickness: formData.partThickness,
            partQuantity: formData.partQuantity,
            partType: formData.partType,
            weldGroove: formData.weldGroove,
            weldMethod: formData.weldMethod,
            baseMaterial1: formData.baseMaterial1,
            baseMaterial2: formData.baseMaterial2,
            weldMaterial: formData.weldMaterial,
            isStatistics: formData.isStatistics,
            note: formData.note,
            attachmentUrl: formData.attachmentUrl
          };

          const res = (await updateOne<ProjectWeldList>(
            urls.projectWeldList,
            tempFormData
          )) as ProjectWeldList;

          if (res) {
            dialogModel.value.change = true;
            formData.updater = res.updater;
            formData.updateTime = res.updateTime;
          }
        }
      }
    })
    .catch(res => console.log(res));
};
</script>
<template>
  <HqDialogDetail
    :dialog-model="dialogModel"
    @submit="saveFormData(formDataRef as FormInstance)"
    operate-record
    :operation="formData"
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <hq-form :model="formData" ref="formDataRef" :rules="formDataRules">
            <el-row :gutter="5">
              <hq-col v-show="false">
                <el-form-item label="id" prop="id">
                  <el-input v-model="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="项目名称" prop="projectId">
                  <el-select v-model="formData.projectId" :disabled="updateForbidden">
                    <HqProjectNameOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="组件名称" prop="componentName">
                  <el-input v-model="formData.componentName" :disabled="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件名称" prop="partName">
                  <el-input v-model="formData.partName" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件编号" prop="partReference">
                  <el-input v-model="formData.partReference" :disabled="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件厚度" prop="partThickness">
                  <el-input-number
                    v-model="formData.partThickness"
                    :min="0"
                    :step="0.01"
                    :disabled="updateForbidden"
                    controls-position="right"
                  >
                    <template #suffix>mm</template>
                  </el-input-number>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件数量" prop="partQuantity">
                  <el-input-number
                    v-model="formData.partQuantity"
                    :min="1"
                    :disabled="updateForbidden"
                  />
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="工件类型" prop="partType">
                  <el-select v-model="formData.partType" :disabled="updateForbidden">
                    <HqDictionary type-text="焊缝类型" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="焊接方法" prop="weldMethod">
                  <el-select v-model="formData.weldMethod" :disabled="updateForbidden" multiple>
                    <HqDictionary type-text="焊接方法" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="母材1牌号" prop="baseMaterial1">
                  <el-select
                    v-model="formData.baseMaterial1"
                    :disabled="updateForbidden"
                    filterable
                  >
                    <HqDictionary type-text="母材牌号" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="母材2牌号" prop="baseMaterial2">
                  <el-select
                    v-model="formData.baseMaterial2"
                    :disabled="updateForbidden"
                    filterable
                  >
                    <HqDictionary type-text="母材牌号" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="焊材牌号" prop="weldMaterial">
                  <el-select
                    v-model="formData.weldMaterial"
                    :disabled="updateForbidden"
                    multiple
                    filterable
                  >
                    <el-option label="N/A" value="N/A" />
                    <HqDictionary type-text="焊材牌号" />
                  </el-select>
                </el-form-item>
              </hq-col>

              <hq-col>
                <el-form-item label="焊接坡口" prop="weldGroove">
                  <el-select v-model="formData.weldGroove" :disabled="updateForbidden">
                    <HqDictionary type-text="焊接坡口" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="合格率统计" prop="isStatistics">
                  <el-switch v-model="formData.isStatistics" :disabled="updateForbidden" />
                </el-form-item>
              </hq-col>
            </el-row>

            <el-row>
              <el-form-item label="备注" prop="note" style="width: 100%">
                <el-input
                  v-model="formData.note"
                  type="textarea"
                  :autosize="{ minRows: 5 }"
                  :readonly="updateForbidden"
                />
              </el-form-item>
            </el-row>
          </hq-form>
        </template>
      </el-card>

      <el-card shadow="hover" v-if="formData.attachmentUuid">
        <template #header>焊缝示意图</template>
        <template #default>
          <HqUploadOne
            :key-word="formData.attachmentUuid"
            :disabled="dialogModel.type !== 'update'"
          />
        </template>
      </el-card>
    </template>
  </HqDialogDetail>
</template>
<style lang="scss" scoped></style>
